Skip to main content

React Testing Library

Setup

npm install --save-dev @testing-library/react

Add Libraries​

"@testing-library/jest-dom": "^5.11.4",  
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"jest": "^26.6.0",

Simple Code​

import {render, screen} from "@testing-library/react";  
import Home from "./Home";
import {QueryClient, QueryClientProvider} from "react-query";


const queryClient = new QueryClient()
describe('Home Page', () => {
it('should render my name', () => {
render(<QueryClientProvider client={queryClient}><Home/></QueryClientProvider>)
screen.getByText("Melchor Tatlonghari")
});
});

Pitfalls​

  • Use MemoryRouter To initialize pages inside React-Router
  • Make sure it runs on pre-commit otherwise there is no purpose

Typescript

setup​

Install libraries​

npm i -D jest typescript && npm i -D ts-jest @types/jest && npx ts-jest config:init && npm test or npx jest

Configurations​

  • config:
  "jest": {
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[jt]s?(x)",
"!**/mock-data/**/*.[jt]s?(x)"
]
},
  • jest.config.js:
    • See definitions of testEnvironment, either node || jsdom
    • use jsdom for web applications.
/** @type {import('ts-jest').JestConfigWithTsJest} */  
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
};

Imports​

  • necessary import per file import '@testing-library/jest-dom'; OR
  • Have a setupTests.ts
// jest-dom adds custom jest matchers for asserting on DOM nodes.  
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

Optional​

  • tsconfig.json
    • Prohibits installation
"exclude": [
"src/**/*.test.ts",
"src/**/*.test.tsx",
]

Pitfalls​

Make sure these files are correct!

  • jestconfig.js
    • moduleDirectories
    • preset - type of configuration
    • moduleNameMapper
  • tsconfig.js

sample​

ts.config

{  
"compilerOptions": {
"target": "es5",
"lib": [
"es6",
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
],
}
{  
"compilerOptions": {
"baseUrl": "./src",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}